package com.jk.vehicle.core.filter;

import com.jk.vehicle.core.utils.FileUtil;
import com.jk.vehicle.core.utils.WebUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 跨站请求伪造过滤器
 *
 * @author KangJian
 * @date 2018/7/19
 */
public class CsrfFilter implements Filter {

	/**
	 * 日志
	 */
	private Logger logger = LogManager.getLogger();

	/**
	 * 白名单
	 */
	private List<String> whiteUrls;

	/**
	 * 白名单计数
	 */
	private int size = 0;

	@Override
	public void init(FilterConfig filterConfig) {
		logger.info("Init CsrfFilter");
		// 读取文件
		String path = CsrfFilter.class.getResource("/").getFile();
		whiteUrls = FileUtil.readFile(path + "white/csrfWhite.txt");
		size = null == whiteUrls ? 0 : whiteUrls.size();
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		try {
			HttpServletRequest req = (HttpServletRequest) request;
			HttpServletResponse res = (HttpServletResponse) response;
			// 获取请求url地址
			String url = req.getRequestURL().toString();
			String referurl = req.getHeader("Referer");
			if (WebUtil.isWhiteRequest(referurl, size, whiteUrls)) {
				chain.doFilter(request, response);
			} else {
				req.getRequestDispatcher("/").forward(req, res);

				// 记录跨站请求日志
				String log = "";
				String date = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
				String clientIp = WebUtil.getHost(req);

				log = "跨站请求---->>>" + clientIp + "||" + date + "||" + referurl + "||" + url;
				logger.warn(log);

				response.setContentType("text/html; charset=UTF-8");
				PrintWriter out = response.getWriter();

				out.println("{\"code\":\"308\",\"msg\":\"错误的请求头信息\"}");
				out.flush();
				out.close();
				return;
			}

		} catch (Exception e) {
			logger.error("doFilter", e);
		}
	}

	@Override
	public void destroy() {
		logger.info("Destroy CsrfFilter");
	}
}
